package com.qing.thread.unsafe;

/**
 * 模拟多人买票 （数据紊乱）
 */
public class BuyTicket {
    public static void main(String[] args) {
        People people = new People();

        new Thread(people, "我").start();
        new Thread(people, "你").start();
        new Thread(people, "黄牛党").start();
    }
}

//每个人
class People implements Runnable {
    //现在只有10张票
    private int ticketNum = 10;
    //false代表无票
    private boolean flag = true;

    @Override
    public void run() {
        while (flag) {
            try {
                isBuy();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    //判断是否可以买票
    // synchronized是同步方法，保证线程安全，锁的是this
    public synchronized void isBuy() throws InterruptedException {
        if (ticketNum <= 0) {
            flag = false;
            return;
        }
        //模拟延时
        Thread.sleep(10);
        System.out.println(Thread.currentThread().getName() + "买到了第" + ticketNum-- + "票");
    }
}
